import React, { useState, useRef, useEffect } from "react";
import "./css/CbChat.scss";
import {
  NavBar,
  Form,
  Button,
  Card,
  Avatar,
  TextArea,
  Selector,
  Tabs,
  Mask,
  Toast,
  SpinLoading,
} from "antd-mobile";
import constant from "./common/Constants";
import util from "./common/Util";
import { useNavigate } from "react-router-dom";
import { CloseCircleOutline, AddOutline } from "antd-mobile-icons";
/**
 * 超博chat
 */
function CbChat() {
  const navigate = useNavigate();
  const chatBoxRef = useRef();
  const textRef = useRef();
  const formRef = useRef(null);
  const uuid = util.randomNum();
  const [activeKey, setActiveKey] = useState(uuid);
  const [tabList, setTabList] = useState([
    {
      title: "对话1",
      key: uuid,
      sessionId: uuid,
      itemList: [],
    },
  ]);

  const [count, setCount] = useState(1);
  const [visible, setVisible] = useState(false);
  const [disabled, setDisabled] = useState(false);

  const options = [
    {
      label: "李秀满",
      value: "09921afa00ea4976adc753b53f9b0072",
    },
  ];
  useEffect(() => {
    if (textRef.current) {
      textRef.current.clear();
    }
    if (chatBoxRef.current) {
      chatBoxRef.current.scrollTop = chatBoxRef.current.scrollHeight;
    }
  }, [tabList]);

  const back = () => {
    navigate("/menuList");
  };

  const closeTab = (key, event) => {
    let newTabList = tabList.filter((item) => {
      return item.key !== key;
    });
    if (newTabList.length >= 1) {
      setActiveKey(newTabList[newTabList.length - 1].key);
      setTabList([...newTabList]);
    }

    event.stopPropagation();
    return false;
  };
  const getActiveTab = () => {
    const arr = tabList.filter((e) => {
      return e.key === activeKey;
    });
    if (arr.length === 0) {
      return null;
    } else {
      return arr[0];
    }
  };
  const send = (o) => {
    console.info(o);
    const tab = getActiveTab();
    const text = textRef.current.nativeElement.value;
    const item = {
      type: "right",
      text: text,
      role: "user",
    };

    tab.itemList = [...tab.itemList, item];
    setTabList([...tabList]);

    setDisabled(true);
    const url = constant.baseUrl + "/app/cbChat";
    const token = util.getToken();
    console.info("token", token);
    if (token == null) {
      navigate("/login");
    }
    const characterId = o.characterId[0];
    let sessionId = tab.sessionId;
    sessionId = "112";
    console.info(sessionId);

    util.postForm(
      url,
      { token, sessionId: sessionId, characterId, text: text },
      (resultObj) => {
        setDisabled(false);

        if (resultObj.code === 50002) {
          localStorage.removeItem("token");
          navigate("/login");
        }
        if (resultObj.code === 0) {
          const resp = resultObj.resp;
          const respItem = {
            type: "left",
            text: resp,
            role: "ai",
          };
          tab.itemList = [...tab.itemList, respItem];
          setTabList([...tabList]);
        } else {
          Toast.show({
            content: "信息:" + resultObj.message,
            position: "top",
          });
        }
      }
    );
  };

  const addTab = (e) => {
    const uuid = util.randomNum();
    let c = count + 1;
    const v = {
      title: "对话" + c,
      key: uuid,
      sessionId: uuid,
      itemList: [],
    };
    setTabList([...tabList, v]);
    setActiveKey(uuid);
    setCount(c);
    e.stopPropagation();
  };
  const changeTab = (e) => {
    setActiveKey(e);
    console.info("切换tab,当前:" + e);
  };

  useEffect(() => {
    formRef.current.setFieldsValue({
      characterId: "09921afa00ea4976adc753b53f9b0072",
    });
  }, []);

  const ret = (
    <div className="CbChat container">
      <NavBar onBack={back} style={{ "--border-bottom": "1px #eee solid" }}>
        文本对话
      </NavBar>
      {/* tab部分 */}
      <div>
        <Tabs stretch={false} activeKey={activeKey} onChange={changeTab}>
          {tabList.map((tab) => {
            return (
              <Tabs.Tab
                title={
                  <div>
                    {tab.title}
                    <span
                      onClick={closeTab.bind(this, tab.key)}
                      style={{ paddingLeft: "10px", display: "inline-block" }}
                    >
                      <CloseCircleOutline fontSize={18} />
                    </span>
                  </div>
                }
                key={tab.key}
              >
                <div className="chat-box" ref={chatBoxRef}>
                  {tab.itemList.length === 0 && <div>提交内容开启对话</div>}

                  {tab.itemList.map((item, index) => {
                    return (
                      <ChatItem
                        item={item}
                        key={tab.key + "-" + index}
                      ></ChatItem>
                    );
                  })}
                </div>
              </Tabs.Tab>
            );
          })}
          <Tabs.Tab
            title={<AddOutline onClick={addTab} />}
            key={"addBtn"}
          ></Tabs.Tab>
        </Tabs>
      </div>

      <Form
        ref={formRef}
        onFinish={send}
        style={{ "--prefix-width": "2.0em" }}
        layout="horizontal"
        mode="card"
        footer={
          <Button
            disabled={disabled}
            block
            type="submit"
            color="primary"
            size="large"
          >
            提交
          </Button>
        }
      >
        <Form.Item
          name="content"
          label="内容"
          rules={[{ required: true }, { type: "string", min: 2 }]}
        >
          <TextArea
            showCount
            ref={textRef}
            placeholder="请输入内容"
            clearable
            maxLength={200}
            rows={4}
            style={{
              border: "1px solid #ccc",
              borderRadius: "5px",
              padding: "5px",
            }}
          />
        </Form.Item>
        <Form.Item label="角色" name="characterId" rules={[{ required: true }]}>
          <Selector
            defaultValue={["09921afa00ea4976adc753b53f9b0072"]}
            options={options}
          />
        </Form.Item>
      </Form>

      <Mask visible={visible}>
        <div className="mask">
          <SpinLoading style={{ "--size": "80px" }} />
        </div>
      </Mask>
    </div>
  );
  return ret;
}

function ChatItem(props) {
  const demoAvatarImages = [
    "https://images.unsplash.com/photo-1548532928-b34e3be62fc6?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ",
    "https://images.unsplash.com/photo-1493666438817-866a91353ca9?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&s=b616b2c5b373a80ffc9636ba24f7a4a9",
    "https://images.unsplash.com/photo-1542624937-8d1e9f53c1b9?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ",
    "https://images.unsplash.com/photo-1546967191-fdfb13ed6b1e?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&ixid=eyJhcHBfaWQiOjE3Nzg0fQ",
  ];
  let { item } = props;
  if (item.type === "left") {
    const leftRet = (
      <div className="chat-item">
        <div className="chat-head">
          <Avatar
            className="chat-head-left"
            src={demoAvatarImages[0]}
            style={{ "--size": "48px" }}
          />
        </div>
        <Card className="chat-text">{item.text}</Card>
        <div className="chat-space"></div>
      </div>
    );

    return leftRet;
  } else if (item.type === "right") {
    const rightRet = (
      <div className="chat-item">
        <div className="chat-space"></div>
        <Card className="chat-text chat-text-right">{item.text}</Card>
        <div className="chat-head">
          <Avatar
            className="chat-head-right"
            src={demoAvatarImages[1]}
            style={{ "--size": "48px" }}
          />
        </div>
      </div>
    );
    return rightRet;
  }
}

export default CbChat;
